package com.beta.mybatis.type;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.time.ZoneOffset;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * Created by vector on 2017/2/6.
 */
public class ShopDateTypeHandler extends BaseTypeHandler<Date> {

    private long dbTimeOffsetMsec = ZoneOffset.ofHours(-8).getLong(ChronoField.OFFSET_SECONDS) * 1000L;

    public ShopDateTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        preparedStatement.setTimestamp(i, toDbTime(date));
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Timestamp sqlTimestamp = resultSet.getTimestamp(columnName);
        return sqlTimestamp != null ? toLocalTime(sqlTimestamp) : null;
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = resultSet.getTimestamp(columnIndex);
        return sqlTimestamp != null ? toLocalTime(sqlTimestamp) : null;
    }

    @Override
    public Date getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = callableStatement.getTimestamp(columnIndex);
        return sqlTimestamp != null ? toLocalTime(sqlTimestamp) : null;
    }

    private Timestamp toDbTime(Date localDate) {
        return new Timestamp(localDate.getTime() + dbTimeOffsetMsec);
    }

    private Date toLocalTime(Timestamp dbTime) {
        return new Date(dbTime.getTime() - dbTimeOffsetMsec);
    }

}
